package com.wangsai.framework.supersecurity.resttemplate;

import com.alibaba.fastjson.JSON;
import com.wangsai.framework.supersecurity.core.SuperSecurityManager;
import com.wangsai.framework.supersecurity.core.context.UserContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Optional;

/**
 * 统一添加 user 拦截器
 *
 * @author Mr.Wang
 * @date 2021-08-16 08:41
 */
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        HttpHeaders headers = httpRequest.getHeaders();
        Optional<HashMap> userOptional = UserContext.currentUserOfNullable(HashMap.class);
        userOptional.ifPresent(user -> headers.add(SuperSecurityManager.getConfig().getUserKey(), SuperSecurityManager.getUserSecure().encode(JSON.toJSONString(user))));
        return clientHttpRequestExecution.execute(httpRequest, body);
    }
}